package memdb

import (
	"fmt"
	"github.com/hashicorp/go-memdb"
	appErr "lib/exception"
	"sync"
)

var once sync.Once
var db *memdb.MemDB
var tables map[string]*memdb.TableSchema

func doInit() appErr.Exception {
	// init
	schema := memdb.DBSchema{Tables: tables}
	memDB, newSchemaErr := memdb.NewMemDB(&schema)
	if newSchemaErr != nil {
		return appErr.NewException(fmt.Sprintf("MemDbInitSchemaErr. Err is %v.", newSchemaErr), 1)
	}
	db = memDB
	return nil
}

func AddTables(tableName string, tableSchema *memdb.TableSchema) (bool, appErr.Exception) {
	once.Do(func() {
		tables = map[string]*memdb.TableSchema{}
	})
	if tables == nil {
		return false, appErr.NewException("", 3)
	}
	if _, existed := tables[tableName]; existed {
		return false, appErr.NewException("", 4)
	}
	tables[tableName] = tableSchema
	return true, nil
}

func Instance() *memdb.MemDB {
	once.Do(func() {
		_ = doInit()
	})
	return db
}
